<template>
	<view class="container" v-if="!loading">
		<view class="main" v-if="goods.length">
			<view class="nav">
				<view class="header">
					<!-- <view class="left" v-if="orderType == 'takein'">
						<view class="store-name">
							<text>{{ store.shopName }}</text>
						</view>
						<view class="store-location">
							<image src="/static/images/order/location.png" style="width: 30rpx; height: 30rpx;" class="mr-10"></image>
							<text>距离您 {{ store.distance_text }}</text>
						</view>
					</view>
					<view class="left overflow-hidden" v-else>
						<view class="d-flex align-items-center overflow-hidden">
							<image src="/static/images/order/location.png" style="width: 30rpx; height: 30rpx;" class="mr-10"></image>
							<view class="font-size-extra-lg text-color-base font-weight-bold text-truncate">
								{{ `${address.provinceName}${address.cityName}${address.areaName}${address.communityName ? address.communityName : ''}${address.address}` }}
							</view>
						</view>
						<view class="font-size-sm text-color-assist overflow-hidden text-truncate">
							由
							<text class="text-color-base" style="margin: 0 10rpx">{{ store.shopName }}</text>
							配送
						</view>
					</view> -->
					<view class="left">
						<view class="store-name">
							<text>{{ store.shopName }}</text>
						</view>
						<view class="store-location">
							<image src="/static/images/order/location.png" style="width: 30rpx; height: 30rpx;" class="mr-10"></image>
							<text>距离您 {{ store.distance_text }}</text>
						</view>
					</view>
					<view class="right" @tap="changeOrderType">
						<view class="dinein" :class="{ active: orderType == 'takein' }"><text>自取</text></view>
						<view class="takeout" :class="{ active: orderType == 'takeout' }"><text>外卖</text></view>
					</view>
				</view>
			</view>
			<view class="content">
				<scroll-view class="menus" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${item.id}`" :class="{ current: item.id === currentCateId }" v-for="(item, index) in goods"
						 :key="index" @tap="handleMenuTap(item.id)">
							<text>{{ item.name }}</text>
							<view class="dot" v-show="menuCartNum(item.id)">{{ menuCartNum(item.id) }}</view>
						</view>
					</view>
				</scroll-view>
				<!-- goods list begin -->
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="cateScrollTop" @scroll="handleGoodsScroll">
					<view class="wrapper">
						<!-- 轮播图 -->
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in ads" :key="index">
								<image :src="item.image"></image>
							</swiper-item>
						</swiper>
						<!-- 商品列表 -->
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="item in goods" :key="item.id" :id="`cate-${item.id}`">
								<view class="title">
									<text>{{ item.name }}</text>
									<image :src="item.icon" class="icon"></image>
								</view>
								<view class="items">
									<!-- 商品 begin -->
									<view class="good" v-for="good in item.goods_list" :key="good.id">
										<image :src="good.imageUrl" class="image" @tap="showGoodDetailModal(item, good)"></image>
										<view class="right">
											<text class="name">{{ good.goodsName }}</text>
											<text class="tips">{{ good.keywords }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ good.marketPrice }}元{{good.goodsUnit?'/'+good.goodsUnit:''}}</text>
												<view class="btn-group" v-if="good.attribute.length">
													<button type="primary" class="btn property_btn" hover-class="none" size="mini" @tap="showGoodDetailModal(item, good)">选规格</button>
													<view class="dot" v-show="goodCartNum(good.id)">{{ goodCartNum(good.id) }}</view>
												</view>
												<view class="btn-group" v-else>
													<button type="default" v-show="goodCartNum(good.id)" plain class="btn reduce_btn" size="mini" hover-class="none"
													 @tap="handleReduceFromCart(item, good)">
														<view class="iconfont iconsami-select"></view>
													</button>
													<view class="number" v-show="goodCartNum(good.id)">{{ goodCartNum(good.id) }}</view>
													<button type="primary" class="btn add_btn" size="min" hover-class="none" @tap="handleAddToCart(item, good, 1)">
														<view class="iconfont iconadd-select"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>
				</scroll-view>
				<!-- goods list end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart && cart.cartList.length">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice }}元</view>
				<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">{{ disabledPay ? `差${spread}元起送` : '去结算' }}</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom padding="0rpx"
		 radius="12rpx">
			<view class="cover">
				<image :src="good.imageUrl" class="image"></image>
				<view class="btn-group">
					<image src="/static/images/menu/share-good.png"></image>
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y>
				<view class="wrapper">
					<view class="basic">
						<view class="name">{{ good.goodsName  }}</view>
						<view class="tips">{{ good.keywords}}</view>
					</view>
					<view class="properties" v-if="good.attribute">
						<view class="property" v-for="(item, index) in good.attribute" :key="index">
							<view class="title">
								<text class="name">{{ item.ggName }}</text>
								<view class="desc" v-if="item.desc">({{ item.desc }})</view>
							</view>
							<view class="values">
								<view class="value" v-for="(value, key) in item.ggList" :key="key" :class="{ default: value.is_default }" @tap="changePropertyDefault(index, key)">
									{{ value.value }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<view class="left">
					<view class="price">￥{{ good.marketPrice }}元{{good.goodsUnit?'/'+good.goodsUnit:''}}</view>
					<view class="props" v-if="getGoodSelectedProps(good)">{{ getGoodSelectedProps(good) }}</view>
				</view>
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="handlePropertyReduce">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ good.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="handlePropertyAdd">
						<view class="iconfont iconadd-select"></view>
					</button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="handleAddToCartInModal">
				<view>加入购物车</view>
			</view>
		</modal>
		<!-- 商品详情模态框 end -->
		<!-- 购物车详情popup -->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup" @change="
				val => {
					this.cartPopupVisible = val;
				}
			">s
			<template slot="content">
				<view class="top"><text @tap="handleCartClear">清空</text></view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper" v-if="cart.cartList">
						<view class="item" v-for="(item, index) in cart.cartList" :key="item.id">
							<view class="left">
								<view class="name">{{ item.goodsName?item.goodsName:''}}</view>
								<view class="props">{{ item.attribute?item.attribute:''}}</view>
							</view>
							<view class="center">
								<text class="price">￥{{ item.marketPrice }}元{{item.goodsUnit?'/'+item.goodsUnit:''}}</text>
							</view>
							<view class="right">
								<button type="default" plain size="mini" class="btn" hover-class="none" @tap="handleCartItemReduce(index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ item.number }}</view>
								<button type="primary" class="btn" size="min" hover-class="none" @tap="handleCartItemAdd(index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
						<view class="item" v-if="orderType == 'takeout' && store.packing_fee">
							<view class="left">
								<view class="name">包装费</view>
							</view>
							<view class="center">
								<text>￥{{ parseFloat(store.packing_fee) }}元</text>
							</view>
							<view class="right invisible">
								<button type="default" plain size="mini" class="btn" hover-class="none">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">1</view>
								<button type="primary" class="btn" size="min" hover-class="none">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popup-layer>
		<!-- 购物车详情popup -->
	</view>
	<view class="loading" v-else>
		<image src="/static/images/loading.gif" />
	</view>
</template>

<script>
	import {
		getDistance
	} from '@/utils';
	import modal from '@/components/modal/modal';
	import popupLayer from '@/components/popup-layer/popup-layer';
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex';
	export default {
		components: {
			modal,
			popupLayer
		},
		data() {
			return {
				goods: [], //所有商品
				ads: [{
						image: require('static/images/menu/banner.jpeg')
					},
					{
						image: require('static/images/menu/banner.jpeg')
					},
					{
						image: require('static/images/menu/banner.jpeg')
					},
					{
						image: require('static/images/menu/banner.jpeg')
					},
					{
						image: require('static/images/menu/banner.jpeg')
					},
				],
				loading: true,
				currentCateId: null, //默认分类
				cateScrollTop: 0,
				cart: {}, //购物车
				goodDetailModalVisible: false, //是否饮品详情模态框
				good: {}, //当前饮品
				category: {}, //当前饮品所在分类
				cartPopupVisible: false,
				sizeCalcState: false
			};
		},
		async onLoad(param) {
			var referrer = param.referrer;
			if (referrer && referrer.length > 0) {
				uni.setStorageSync('pid', referrer);
				//console.log('pid', referrer);
			}
			await this.init();
		},
		async onShow() {
			if (this.isLogin) {
				const cartInfo = await this.cartIndex().then(res => res.data.data);
				this.cart = cartInfo;
			}
		},
		onShareAppMessage(res) {
			let referrer = uni.getStorageSync('referrer');
			//console.log('referrer', referrer);
			if (referrer) {
				return {
					title: '恒鲜惠美食在线',
					path: '/pages/menu/menu?referrer=' + referrer,
					imageUrl: require('static/images/menu/banner.jpeg')
				}
			}
		},
		computed: {
			...mapGetters(['isLogin', 'orderType', 'address', 'store']),

			//计算单个饮品添加到购物车的数量
			goodCartNum(id) {
				return id =>
					this.cart.cartList &&
					this.cart.cartList.reduce((acc, cur) => {
						if (cur.goodsId === id) {
							return (acc += cur.number);
						}
						return acc;
					}, 0);
			},
			menuCartNum() {
				return id =>
					this.cart.cartList &&
					this.cart.cartList.reduce((acc, cur) => {
						if (cur.categoryId === id) {
							return (acc += cur.number);
						}
						return acc;
					}, 0);
			},
			getCartGoodsNumber() {
				//计算购物车总数
				return this.cart.cartTotal && this.cart.cartTotal.goodsCount;
			},
			getCartGoodsPrice() {
				//计算购物车总价
				return this.cart.cartTotal && this.cart.cartTotal.goodsAmount;
			},
			disabledPay() {
				//是否达到起送价
				return this.orderType == 'takeout' && this.getCartGoodsPrice < this.store.freightPrice ? true : false;
			},
			spread() {
				//差多少元起送
				if (this.orderType != 'takeout') return;
				return parseFloat((this.store.freightPrice - this.getCartGoodsPrice).toFixed(2));
			}
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE', 'SET_STORE', 'SET_ADDRESS']),
			...mapActions(['goodList', 'categoryList', 'shopInfo', 'goodsDetail', 'cartAdd', 'cartIndex', 'cartMinus',
				'cartCheckOut', 'cartCLear'
			]),
			async init() {
				//页面初始化
				this.loading = true;
				//商品类别
				let categorys = await this.categoryList().then(res => res.data.categoryList || []);
				//商品
				let goods = await this.goodList().then(res => res.data.goodsList || []);
				//商店数据
				await this.shopInfo();

				this.goods = categorys.map(item => {
					item.goods_list = [];
					goods.forEach(good => {
						if (good.categoryId === item.id) {
							if (good.attribute && good.attribute.length) {
								good.attribute = JSON.parse(good.attribute).map(c => {
									c.ggList = c.ggList.map((g, i) => {
										let obj = new Object();
										obj.value = g;
										if (!i) {
											obj.is_default = 1;
										} else {
											obj.is_default = 0;
										}
										return obj;
									});
									return c;
								});
							}
							item.goods_list.push(good);
						}
					});
					return item;
				});
				this.currentCateId = this.goods[0].id;
				uni.getLocation({
					type: 'gcj02',
					altitude: true
				}).then(async ([err, suc]) => {
					let shopInfo = this.store;
					if (err) {
						shopInfo.distance_text = `用户取消定位授权`;
					}
					if (suc) {
						await this.shopInfo({
							lng: suc.longitude,
							lat: suc.latitude
						});
						shopInfo.distance_text = `${getDistance(suc.latitude, suc.longitude, shopInfo.lat, shopInfo.lng)}公里`;
					}
					this.SET_STORE(shopInfo);
					this.loading = false;
				});
			},
			handleMenuTap(id) {
				//点击菜单项事件
				if (!this.sizeCalcState) {
					this.calcSize();
				}
				this.currentCateId = id;
				this.$nextTick(() => (this.cateScrollTop = this.goods.find(item => item.id == id).top));
			},
			handleGoodsScroll({
				detail
			}) {
				//商品列表滚动事件
				if (!this.sizeCalcState) {
					this.calcSize();
				}
				const {
					scrollTop
				} = detail;
				let tabs = this.goods.filter(item => item.top <= scrollTop).reverse();
				if (tabs.length > 0) {
					this.currentCateId = tabs[0].id;
				}
			},
			calcSize() {
				let h = 10;
				let view = uni.createSelectorQuery().select('#ads');
				view
					.fields({
						size: true
					}, data => {
						h += Math.floor(data.height);
					})
					.exec();
				this.goods.forEach(item => {
					let view = uni.createSelectorQuery().select(`#cate-${item.id}`);
					view
						.fields({
							size: true
						}, data => {
							console.log(data);
							item.top = h;
							h += data.height;
							item.bottom = h;
						})
						.exec();
				});
				this.sizeCalcState = true;
			},
			handleAddToCart(cate, good, num) {
				console.log('good', good)
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/login/login'
					});
					return false;
				}
				uni.showLoading({
					mask: true
				});
				this.cartAdd({
					attribute: good.props_text ? good.props_text.split('，') : good.attribute,
					goodsId: good.id,
					number: num
				}).then(res => {
					this.cart = res.data.data;
					console.log('car', this.cart)
					uni.hideLoading();
				});
			},
			handleReduceFromCart(item, good) {
				uni.showLoading({
					mask: true
				});
				this.cartMinus({
					goodsId: good.id,
					number: 1
				}).then(res => {
					this.cart = res.data.data;
					uni.hideLoading();
				});
			},
			showGoodDetailModal(item, good) {
				this.good = JSON.parse(JSON.stringify({ ...good,
					number: 1
				}));
				console.log('good', good)
				this.category = JSON.parse(JSON.stringify(item));
				this.goodDetailModalVisible = true;
				uni.hideTabBar({
					animation: true
				});
			},
			closeGoodDetailModal() {
				//关闭饮品详情模态框
				this.goodDetailModalVisible = false;
				uni.showTabBar({
					animation: true
				});
				this.category = {};
				this.good = {};
			},
			changePropertyDefault(index, key) {
				//改变默认属性值
				this.good.attribute[index].ggList.forEach(value => this.$set(value, 'is_default', 0));
				this.good.attribute[index].ggList[key].is_default = 1;
				this.good.number = 1;
			},
			getGoodSelectedProps(good, type = 'text') {
				//计算当前饮品所选属性
				if (good.attribute && good.attribute.length) {
					let props = [];
					good.attribute.forEach(({
						ggName,
						ggList
					}) => {
						ggList.forEach(value => {
							if (value.is_default) {
								props.push(`${ggName}:${value.value}`);
							}
						});
					});
					return type === 'text' ? props.join('，') : props;
				}
				return '';
			},
			handlePropertyAdd() {
				this.good.number += 1;
			},
			handlePropertyReduce() {
				if (this.good.number === 1) return;
				this.good.number -= 1;
			},
			handleAddToCartInModal() {
				const product = Object.assign({}, this.good, {
					props_text: this.getGoodSelectedProps(this.good)
				});
				this.handleAddToCart(this.category, product, this.good.number);
				this.closeGoodDetailModal();
			},
			openCartPopup() {
				//打开/关闭购物车列表popup
				this.cartPopupVisible = !this.cartPopupVisible;
			},
			handleCartClear() {
				//清空购物车
				uni.showModal({
					title: '提示',
					content: '确定清空购物车么',
					success: ({
						confirm
					}) => {
						if (confirm) {
							uni.showLoading({
								mask: true
							});
							this.cartCLear().then(res => {
								uni.hideLoading();
								this.cart = res.data.data;
								this.cartPopupVisible = false;
							});
						}
					}
				});
			},
			handleCartItemAdd(index) {
				const gd = this.cart.cartList[index];
				uni.showLoading({
					mask: true
				});
				this.cartAdd({
					attribute: gd.attribute,
					goodsId: gd.goodsId,
					number: 1
				}).then(res => {
					this.cart = res.data.data;
					uni.hideLoading();
				});
			},
			handleCartItemReduce(index) {
				const gd = this.cart.cartList[index];
				if (gd.number === 1) {
					uni.showLoading({
						mask: true
					});
					this.cartMinus({
						goodsId: gd.goodsId,
						number: 1
					}).then(res => {
						this.cart = res.data.data;
						uni.hideLoading();
						if (!this.cart.cartList.length) {
							this.cartPopupVisible = false;
						}
					});
				} else {
					uni.showLoading({
						mask: true
					});
					this.cartMinus({
						goodsId: gd.goodsId,
						number: 1
					}).then(res => {
						this.cart = res.data.data;
						uni.hideLoading();
					});
				}
			},
			toPay() {
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/login/login'
					});
					return;
				}
				uni.showLoading({
					title: '加载中'
				});
				let shopInfo = this.store;
				this.cartCheckOut({
					freightDistance: this.orderType == 'takein' ? 0 : this.store.distance_text.replace('公里', ''),
					shopId: shopInfo.id,
					address: ""
				}).then(res => {
					uni.hideLoading();
					console.log('res', res)
					if (res.code == 0) { //校验成功
						if (res.data.checkedAddress.id) { //有默认收货地址
							const payinfo = Object.assign({}, {
								payinfo: res.data
							});
							console.log('payinfo', payinfo)
							this.SET_ADDRESS(res.data.checkedAddress);
							uni.setStorageSync('cart', payinfo);
							uni.navigateTo({
								url: '/pages/pay/pay'
							});
						} else { //无收货地址
							uni.showToast({
								title: '无收货地址，以为您跳转',
								mask: true,
								duration: 1500,
								icon: 'none',
								complete: () => {
									setTimeout(function() {
										uni.navigateTo({
											url: '/pages/address/add'
										});
									}, 1500)
								}
							})

						}
					} else if (res.code == 400) { //商品库存不足
						uni.showToast({
							title: '商品库存不足',
							mask: true,
							duration: 1500
						})
					}

				});
			},
			changeOrderType() {
				//判断是否登录状态
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/login/login'
					});
					return;
				}
				if (this.orderType === 'takein') {
					this.SET_ORDER_TYPE('takeout');
					/* uni.navigateTo({
						url: '/pages/address/address?is_choose=true'
					}); */
				} else if (this.orderType == 'takeout') {
					this.SET_ORDER_TYPE('takein');
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import './menu.scss';
</style>
